<template>
  <base-breadcrumb class="">
    <!-- 方案审核师管理 -->
    <a-spin :spinning="loading">
      <a-card :bordered="false">
        <title-name title="会议发起"></title-name>
        <custom-form
          ref="customForm"
          :isEmit="false"
          :form="form"
          :edit-model="'E'"
          :form-list="formList"
          :rules="rules"
          is-validate
        />
      </a-card>
      <!-- 表格 -->
      <a-card
        v-if="type!=='todo'"
        :bordered="false"
      >
        <title-name title="评审方案列表"></title-name>

        <a-button
          v-if="editable"
          @click="handleDetial('add')"
          type="primary"
          v-btnPermission="'tm_009_add_01'"
        >添加方案</a-button>

        <excel
          v-if="!editable"
          ref="exportBtn"
          :file-name="form.meetingName"
          is-click-generate="false"
        >
          <a-button
            slot="excelBtn"
            type="primary"
            class="mb12"
            :loading="isExport"
            @click="handleExport"
          >
            导出
          </a-button>
        </excel>

        <a-table
          :columns="columns"
          :data-source="tableData"
          :pagination="false"
        >

          <span
            slot="serial"
            slot-scope="text, record, index"
          >{{ index + 1 }}</span>

          <template slot="filesTitle">
            <div style="text-align: center;">
              附件<div style="color: #D9001B;">(联审方案电子版或扫描件、汇报ppt)</div>
            </div>
          </template>

          <template
            slot="files"
            slot-scope="text, record"
          >
            <div v-for="(item, index) in getTableFile(record)">
              <a-popover
                v-if="item"
                :key="item.fileId"
                placement="top"
              >
                <template slot="content">
                  <a
                    :fileId="item.fileId"
                    :fileName="item.fileName"
                    :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + item.fileId"
                    target="_parent"
                  >下载</a>
                  <a-divider type="vertical" />
                  <a
                    :key="item.fileId"
                    @click="$filePreview(item)"
                  >查看</a>
                </template>
                <a-button
                  size="small"
                  type="link"
                >
                  {{ item.fileName + item.suffixName }}
                </a-button>
              </a-popover>
              <span v-else>dsdsd</span>
            </div>
          </template>

          <template
            slot="mainPeopleName"
            slot-scope="text, record"
          >
            <span>{{(text && text.length) ? text.join('、') : ''}}</span>
          </template>

          <!-- 操作 -->
          <template
            slot="operation"
            slot-scope="text, record"
          >
            <span v-if="editable">
              <a @click="handleDetial('edit', record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleDelete(record)">删除</a>
            </span>
            <span v-else>
              <service-export-mould
                url="/program-meet/plans/print"
                :requestParams="{ id: record.id }"
                icon="cloud-download"
                :serviceiUrl="technicalApiUrl"
                :isButton="false"
              ></service-export-mould>
            </span>
          </template>
        </a-table>
      </a-card>

      <a-card
        v-if="type!=='todo' && form.programOptionSerVOS && form.programOptionSerVOS.length"
        :bordered="false"
      >
        <title-name title="联审意见"></title-name>
        <a-form-model
          ref="optionForm"
          :model="optionForm"
        >
          <a-tabs :tab-position="'left'">
            <a-tab-pane
              v-for="(item, index) in this.form.programOptionSerVOS"
              :key="index"
              :tab="item.name"
            >
              <span v-for="(sub, idx) in item.optionDTOS">
                <a-divider v-if="index > 0" />
                <a-row type="flex">
                  <a-col :span="8">
                    <a-form-model-item
                      style="display: flex;"
                      label="主评专家"
                    >
                      {{sub.userName}}
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item
                      style="display: flex;"
                      label="评审得分"
                    >
                      {{sub.score}}
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-model-item
                      style="display: flex;"
                      label="评审意见"
                    >
                      <BaseTextarea
                        disabled
                        v-model="sub.programOptions"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-model-item
                      style="display: flex;"
                      label="附件上传"
                    >
                      <UploadList
                        businessCode="TM05"
                        :uploadArrys="sub.fileList"
                        :disabled="true"
                        :isShow="false"
                      >
                      </UploadList>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </span>
            </a-tab-pane>
          </a-tabs>
        </a-form-model>
      </a-card>

      <a-card
        v-if="type=='todo'"
        :bordered="false"
      >
        <title-name title="评审方案"></title-name>
        <a-form-model
          ref="optionForm"
          :model="optionForm"
        >
          <span
            v-for="(item, index) in optionForm.formObj"
            :key="item.id"
          >
            <a-divider v-if="index > 0" />
            <a-row type="flex">
              <a-col :span="8">
                <a-form-model-item
                  style="display: flex;"
                  label="所属分公司"
                >
                  <BaseInput
                    disabled
                    v-model="item.planSerDTO.branchComName"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  style="display: flex;"
                  label="所属项目"
                >
                  <BaseInput
                    disabled
                    v-model="item.planSerDTO.projectName"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  style="display: flex;"
                  label="方案名称"
                >
                  <BaseInput
                    disabled
                    v-model="item.name"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  style="display: flex;"
                  label="方案类别"
                >
                  <BaseInput
                    disabled
                    v-model="item.planSerDTO.programTypeName"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  style="display: flex;"
                  label="编制时间"
                >
                  <BaseInput
                    disabled
                    v-model="item.planSerDTO.submitDate"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  style="display: flex;"
                  label="项目总工"
                >
                  <BaseInput
                    disabled
                    v-model="item.planSerDTO.zgName"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  style="display: flex;"
                  label="专业类别"
                >
                  <BaseInput
                    disabled
                    v-model="item.planSerDTO.professional"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  style="display: flex;"
                  label="主评专家"
                >
                  <BaseInput
                    disabled
                    v-model="item.planSerDTO.mainPeopleName.join(',')"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  style="display: flex;"
                  label="方案电子版或扫描件"
                >
                  <UploadList
                    businessCode="TM05"
                    :uploadArrys.sync="item.planSerDTO.pictures"
                    :disabled="true"
                    :isShow="false"
                  ></UploadList>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  style="display: flex;"
                  label="评审汇报PPT"
                >
                  <UploadList
                    businessCode="TM05"
                    :uploadArrys.sync="item.planSerDTO.rectificationPicture"
                    :disabled="true"
                    :isShow="false"
                  ></UploadList>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  style="display: flex;"
                  label="其它"
                >
                  <UploadList
                    businessCode="TM05"
                    :disabled="true"
                    :isShow="false"
                    :uploadArrys.sync="item.planSerDTO.otherPicture"
                  ></UploadList>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  style="display: flex;"
                  label="评审意见"
                  :prop="'formObj.' + index + '.programOptions'"
                  :rules="{ required: true, message: '请填写评审意见', trigger: 'blur'}"
                >
                  <BaseTextarea
                    v-model="item.programOptions"
                    :disabled="resolveInfo"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  style="display: flex;"
                  label="评审得分(a)"
                  :prop="'formObj.' + index + '.score'"
                  :rules="{ required: true, message: '请填写评审得分', trigger: 'blur'}"
                >
                  <BaseInputNumber
                    v-model="item.score"
                    :disabled="resolveInfo"
                    placeholder="0<100"
                    :min="0"
                    :max="100"
                  />
                  <span style="position: absolute; width: 450px;color: #D9001B;"> a&gt;=90分，优秀；80&gt;=a&lt;90,良好；60&gt;=a&lt;80,及格；a&lt;60,不及格 </span>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  style="display: flex;"
                  :prop="'formObj.' + index + '.fileList'"
                  label="附件上传"
                >
                  <!-- :rules="{ required: true, type: 'array', message: '请上传附件', trigger: 'change'}" -->
                  <UploadList
                    :disabled="resolveInfo"
                    businessCode="TM05"
                    :uploadArrys.sync="item.fileList"
                    @fileArrysData="(e) => { optionsFilesChange(e, 'formObj.' + index + '.fileList') }"
                  ></UploadList>
                </a-form-model-item>
              </a-col>
            </a-row>
          </span>
        </a-form-model>
      </a-card>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div class="btn_box page-btn-right-top">
      <a-button
        :loading="todoloading"
        v-if="type=='todo' && !resolveInfo"
        type="primary"
        class="button_right"
        @click="todo"
      >
        结束填报
      </a-button>
      <a-button
        :disabled="loading"
        :loading="defloading"
        v-if="editable && !resolveInfo"
        type="primary"
        class="button_right"
        @click="save"
      >
        保存草稿
      </a-button>
      <a-button
        :disabled="loading"
        :loading="subloading"
        v-if="editable && !resolveInfo"
        type="primary"
        class="button_right"
        @click="handleSubmit(1)"
      >
        提交
      </a-button>
      <a-button @click="$close">
        关闭
      </a-button>
    </div>
    <dialog-model
      ref="dialogForm"
      :visible.sync="visible.programForm"
      :edit-model="editModel"
      :forms="programForm"
      @confirm="refreshTable"
    >
    </dialog-model>
  </base-breadcrumb>
</template>

<script>
import moment from 'moment'
import ServiceExportMould from '@/components/ServiceExportMould'
import { finishBusinessTodo, getAllBranchCompany } from '@/api/commons.js'
import { getProgramMeetList, programMeetAdd, programMeetUpdate, getProgramMeetDetail, getProgramMeetOptionDetail, programOptionUpdate, print } from '@/api/technical/meeting'
import UploadList from '@/components/UploadList'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import DialogModel from './DialogModel.vue'
import { technicalApiUrl } from '@/api/config.js'

import Vue from 'vue'
const columns = [
  {
    title: '序号',
    width: '65px',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '分公司',
    dataIndex: 'branchComName',
    key: 'branchComName'
  },
  {
    title: '项目名称',
    dataIndex: 'projectName'
  },
  {
    title: '方案名称',
    dataIndex: 'programName'
  },
  {
    title: '方案类型',
    dataIndex: 'programTypeName'
  },
  {
    title: '编制时间',
    dataIndex: 'submitDate'
  },
  {
    // title: '附件',
    dataIndex: 'files',
    slots: { title: 'filesTitle' },
    scopedSlots: { customRender: 'files' }
  },
  {
    title: '项目总工',
    dataIndex: 'zgName'
  },
  {
    title: '专业',
    dataIndex: 'professional'
  },
  {
    title: '主评专家',
    dataIndex: 'mainPeopleName',
    scopedSlots: { customRender: 'mainPeopleName' }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    fixed: 'right',
    width: '120px',
    scopedSlots: { customRender: 'operation' }
  }
]
export default {
  name: 'a' + Date.now(),
  components: {
    ServiceExportMould,
    SelectSubCompany,
    SelectProject,
    SelectPersonByProject,
    UploadList,
    DialogModel
  },
  data() {
    this.columns = columns
    return {
      technicalApiUrl: technicalApiUrl,
      token: '',
      visible: {
        programForm: false
      },
      editModel: 'add',
      loading: false, // 加载控件
      defloading: false,
      subloading: false,
      todoloading: false,
      printLoading: false,
      isExport: false,
      form: {
        orgId: '',
        orgName: '',
        meetingName: '',
        speaker: '',
        speakerId: '',
        meetOption: '',
        meetDate: '',
        address: '',
        evaluationPlanList: []
      }, // 表单
      rules: {
        speakerId: [{ required: true, message: '请选择主持人/主讲人', trigger: 'change' }],
        address: [{ required: true, message: '请输入会议地点', trigger: 'blur' }],
        meetDate: [{ required: true, message: '请选择会议时间', trigger: 'change' }],
        meetOption: [{ required: true, message: '请输入会议说明', trigger: 'blur' }]
      }, // 校验规则

      tableData: [],
      programForm: {
        // // // 分公司id
        // branchComId: '',
        // // 分公司名称
        // branchComName: '',
        // // 项目id
        // projectId: undefined,
        // // 项目名称
        // projectName: undefined,
        // // 方案类别Id
        // programTypeId: undefined,
        // // 方案类别Name
        // programTypeName: undefined,
        // // 方案id
        // programId: undefined,
        // // 方案id
        // programName: undefined,
        // submitDate: undefined,
        // // 总工id
        // zgId: undefined,
        // // 总工名称
        // zgName: undefined,
        // // 主平专家id
        // mainPeopleId: [],
        // // 主平专家名称
        // mainPeopleName: [],
        // // 专业类别
        // professional: undefined,

        pictures: [],
        rectificationPicture: [],
        otherPicture: []
      },
      programFormRules: {
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }]
      },
      optionTable: [],
      optionForm: {
        formObj: []
      },
      printContent: '',
      companyList: []
    }
  },

  mounted() {
    this.token = Vue.getAcloudProvider().getAccessToken()
    this.querCompany()
    if (this.type == 'add') {
      let curOrg = this.$currentPost()
      this.form.orgId = curOrg?.orgId
      this.form.orgName = curOrg?.orgName
      const param = {
        recordDateBegin: moment().startOf('year').format('YYYY-MM-DD'),
        recordDateEnd: moment().format('YYYY-MM-DD'),
        query: {
          orgId: this.form.orgId
        }
      }
      getProgramMeetList(param).then((res) => {
        if (res.code == 200) {
          this.form.meetingName = moment().startOf('year').format('YYYY年') + '第' + (res.totalSize + 1) + '次重大方案联审'
        }
      })
    } else if (this.type == 'todo') {
      getProgramMeetOptionDetail(this.$route.query.id).then((res) => {
        if (res.code == 200) {
          this.optionForm.formObj = res.data
        }
      })
      this.getDetail()
    } else {
      this.getDetail()
    }
  },
  computed: {
    // 是否是业务待办查看处理信息
    resolveInfo: {
      get() {
        return this.$route.query?.resolveInfo === 'true'
      },
      set() {}
    },
    type() {
      return this.$route.query.type
    },
    editable() {
      return this.type == 'add' || this.type == 'edit'
    },
    curTagCode() {
      return this.$currentPost().id
    },
    curEmployee() {
      return this.$userInfo().employee.levels
    },
    ownOrgList() {
      let levels = [...this.$userInfo().employee.levels]
      let ownOrg = levels.filter((v) => {
        return v.code === 'CO' || v.code === 'BC'
      })
      ownOrg.forEach((v) => {
        if (v.code == 'CO') v.name = '总部机关'
      })
      return ownOrg
    },
    curTableKey() {
      return 'localId'
      // return this.type == 'add' ? 'localId' : 'id'
    },
    formList() {
      return [
        {
          type: 'a-select',
          keyName: 'orgId',
          label: '所属组织机构',
          disabled: true,
          data: this.companyList,
          replaceFields: {
            label: 'name',
            value: 'id'
          }
        },
        {
          keyName: 'meetingName',
          type: 'a-input',
          disabled: true,
          label: '会议名称'
        },
        { span: 8 },
        {
          keyName: 'speakerId',
          // type: 'a-input',
          type: SelectPersonByProject,
          disabled: !this.editable,
          label: '主持人/主讲人',
          attrs: {
            isOrg: true,
            orgId: this.form.orgId,
            showSearch: true,
            isProject: false
          },
          personChanged: (e) => {
            this.form.speaker = e.employeeName
          }
        },
        {
          keyName: 'address',
          type: 'a-input',
          disabled: !this.editable,
          label: '会议地点'
        },
        {
          keyName: 'meetDate',
          type: 'a-date-picker',
          label: '会议时间',
          disabled: !this.editable,
          attrs: {
            valueFormat: 'YYYY-MM-DD HH:mm',
            showTime: { format: 'HH:mm', valueFormat: 'HH:mm' },
            format: 'YYYY-MM-DD HH:mm'
          }
        },
        {
          keyName: 'meetOption',
          span: 24,
          type: 'BaseTextarea',
          disabled: !this.editable,
          label: '会议说明'
        }
      ]
    }
  },
  methods: {
    querCompany() {
      getAllBranchCompany({ tagCodes: ['BC'] }).then((res) => {
        let co = [
          {
            id: '53085e2c9f1f4685801ef31994f57c49',
            name: '总部机关'
          }
        ]
        res.data = [...co, ...res.data]
        let datas = res.data.map((item, index) => {
          item.label = item.name
          item.value = item.id
          return item
        })
        this.companyList = datas
      })
    },
    genID(length) {
      return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36)
    },
    handleDetial(type, record) {
      this.editModel = type
      if (type == 'add') {
        this.programForm = {}
        this.$set(this.programForm, this.curTableKey, this.genID(18))
        // this.$set(this.programForm, 'branchComId', this.form.orgId)
        // this.$set(this.programForm, 'branchComName', this.form.orgName)
      } else {
        this.programForm = { ...record }
      }
      this.visible.programForm = true
    },
    handleDelete(record) {
      this.tableData.forEach((item, idx) => {
        if (item[this.curTableKey] == record[this.curTableKey]) {
          this.tableData.splice(idx, 1)
        }
      })
      // this.tableData = this.tableData.filter(v => v.locakId !== record.locakId)
      //this.$refs.table.refresh()
    },
    refreshTable(e) {
      const row = this.tableData.find((v) => v[this.curTableKey] == e[this.curTableKey])
      if (row) {
        this.tableData = this.tableData.map((v) => {
          if (v[this.curTableKey] == e[this.curTableKey]) {
            v = { ...e }
          }
          return v
        })
      } else {
        this.tableData.push({ ...e })
      }
    },
    getDetail() {
      getProgramMeetDetail(this.$route.query.id).then((res) => {
        if (res.code == 200) {
          const data = res.data
          this.form = data
          if (data.evaluationPlanList) {
            this.tableData = data.evaluationPlanList.map((v) => {
              v[this.curTableKey] = v.id
              return v
            })
          }
          console.log( this.tableData)
        }
      })
    },
    getTableFile(record) {
      let pictures = record.pictures || []
      let rectificationPicture = record.rectificationPicture || []
      let otherPicture = record.otherPicture || []
      return [...pictures, ...rectificationPicture, ...otherPicture]
    },
    optionsFilesChange(e, prop) {
      this.$refs.optionForm.validateField(prop)
    },
    todo() {
      this.$refs.optionForm.validate((valid) => {
        if (valid) {
          this.todoloading = true
          programOptionUpdate(this.optionForm.formObj)
            .then((res) => {
              if (res.code == 200 || res.data.code == 200) {
                return finishBusinessTodo({
                  id: this.$route.query.msgId
                })
              }
            })
            .then((res) => {
              this.todoloading = false
              this.$message.success('提交成功')
              this.$close()
            })
            .catch(() => {
              this.todoloading = false
            })
        } else {
          this.$message.warning("请填写完所有必填项信息")
          return false
        }
      })
    },
    save(back = true) {
      const params = { ...this.form }
      params.evaluationPlanList = [...this.tableData]
      params.auditStatus = 'DRAFT'
      this.defloading = true
      const api = this.type == 'add' ? programMeetAdd : programMeetUpdate
      api(params)
        .then((res) => {
          this.defloading = false
          if (res.code == 200) {
            this.$message.success('保存草稿成功')
            if (back) {
              this.$close()
            } else {
              this.getDetail()
            }
          }
        })
        .catch(() => {
          this.defloading = false
        })
    },
    handleSubmit() {
      this.$refs.customForm.validate((valid) => {
        if (valid) {
          const params = { ...this.form }
          params.evaluationPlanList = [...this.tableData]

          if (params.evaluationPlanList.length == 0) {
            this.$message.error('请添加方案')
            return
          }
          params.auditStatus = 'SUBMITTED'
          const api = this.type == 'add' ? programMeetAdd : programMeetUpdate
          const msg = this.type == 'add' ? '添加' : '编辑'
          this.subloading = true
          api(params)
            .then((res) => {
              this.subloading = false
              if (res.code == 200) {
                this.$message.success(msg + '成功')
                this.$close()
              }
            })
            .catch(() => {
              this.subloading = false
            })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    handleExport() {
      try {
        if (this.isExport) return
        this.isExport = true
        // 分公司、项目名称、方案名称、附件、方案类型、项目总工、专业、主评专家
        // branchComName、projectName、programName、files、programTypeName、zgName、professional、mainPeopleName
        const columns = [
          { title: '分公司', dataIndex: 'branchComName' },
          { title: '项目名称', dataIndex: 'projectName' },
          { title: '方案名称', dataIndex: 'programName' },
          { title: '附件(联审方案电子版或扫描件、汇报ppt)', dataIndex: 'files' },
          { title: '方案类型', dataIndex: 'programTypeName' },
          { title: '项目总工', dataIndex: 'zgName' },
          { title: '专业', dataIndex: 'professional' },
          { title: '主评专家', dataIndex: 'mainPeopleName' }
        ]
        const list = this.tableData.map((item, index) => {
          let files = this.getTableFile(item)
          item.files = files.map((v) => v.fileName + v.suffixName)
          return item
        })
        this.$refs.exportBtn.generateExcel(list, { columns }, 0)

        this.isExport = false
      } catch (e) {
        console.error(e)
        this.isExport = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
